package com.alex.server.service.impl;

import com.alex.server.domain.Category;
import com.alex.server.domain.CategoryExample;
import com.alex.server.domain.ChapterExample;
import com.alex.server.dto.CategoryDto;
import com.alex.server.dto.PageDto;
import com.alex.server.mapper.CategoryMapper;
import com.alex.server.service.ICategoryService;
import com.alex.server.util.CopyUtil;
import com.alex.server.util.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
@Transactional
public class CategoryServiceImpl implements ICategoryService {

    @Autowired
    private CategoryMapper mapper;

    @Override
    public PageDto list(PageDto pageDto) {
        PageHelper.startPage(pageDto.getPage(),pageDto.getSize());
        List<Category> categoryList = mapper.selectByExample(null);
        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);
        pageDto.setTotal(pageInfo.getTotal());
        List<CategoryDto> categoryDtoList = CopyUtil.copyList(categoryList, CategoryDto.class);
        pageDto.setList(categoryDtoList);
        return pageDto;
    }

    /**
     * 列表查询查全部
     * @return
     */
    @Override
    public List<CategoryDto> all() {
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("sort asc");
        List<Category> categoryList = mapper.selectByExample(categoryExample);
        List<CategoryDto> categoryDtoList = CopyUtil.copyList(categoryList, CategoryDto.class);
        return categoryDtoList;
    }

    @Override
    public void save(CategoryDto categoryDto) {
        Category category = CopyUtil.copy(categoryDto, Category.class);
        if (StringUtils.isEmpty(categoryDto.getId())){
            this.insert(category);
        } else {
            this.update(category);
        }
    }

    @Override
    public void insert(Category category) {
        category.setId(UuidUtil.getShortUuid());
        mapper.insert(category);
    }

    @Override
    public void update(Category category) {
        mapper.updateByPrimaryKey(category);
    }

    @Override
    public void delete(String id) {
        deleteChildren(id);
        mapper.deleteByPrimaryKey(id);
    }

    /**
     * 删除子节点分类
     * @param id
     */
    @Override
    public void deleteChildren(String id) {
        Category category = mapper.selectByPrimaryKey(id);
        if ( "00000000".equals(category.getParent())) {
            //如果是一级分类需删除二级分类
            CategoryExample categoryExample = new CategoryExample();
            categoryExample.createCriteria().andParentEqualTo(category.getId());
            mapper.deleteByExample(categoryExample);
        }
    }

}